//
//  SearchViewController.m
//  ShrimpCrowdordering
//
//  Created by 郑洲 on 2018/8/23.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "SearchViewController.h"

#import "SearchCollectionViewCell.h"

#import "EqualCellSpaceFlowLayout.h"

@interface SearchViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate>{
    UITextField *searchField;
    UIView *nullView;
}

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *searchRecords;

@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getSearchRecords];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenX375(33), ScreenX375(30))];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(10), ScreenX375(8), ScreenX375(16), ScreenX375(15))];
    imageView.image = ImageWithName(@"搜索");
    [leftView addSubview:imageView];
    
    if (!searchField) {
        searchField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(46), STATUS_BAR_HEIGHT + ScreenX375(6), ScreenX375(275), ScreenX375(30))];
        searchField.layer.cornerRadius = ScreenX375(15);
        searchField.backgroundColor = RGBACOLOR(238, 238, 238, 0.83);
        searchField.layer.masksToBounds = YES;
        searchField.leftView = leftView;
        searchField.leftViewMode = UITextFieldViewModeAlways;
        searchField.placeholder = @"喜欢什么就搜一搜";
        searchField.returnKeyType = UIReturnKeySearch;
        searchField.font = Kfont(14);
        searchField.tag = 666;
        searchField.delegate = self;
    }
    self.navigationItem.titleView = searchField;
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(16), 0, ScreenX375(100), ScreenX375(44))];
    noteLabel.text = @"历史搜索";
    noteLabel.font = Kfont(13);
    noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
    [self.view addSubview:noteLabel];
    
    UIButton *deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(33), ScreenX375(15), ScreenX375(23), ScreenX375(20))];
    [deleteBtn setImage:ImageWithName(@"删除2") forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(removeHistory) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:deleteBtn];
    
    EqualCellSpaceFlowLayout *flowLayout = [[EqualCellSpaceFlowLayout alloc] initWithType:AlignWithLeft betweenOfCell:ScreenX375(10)];
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, ScreenX375(44), SCREEN_WIDTH, SCREEN_HEIGHT - ScreenX375(44)) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.scrollEnabled = NO;
    [_collectionView registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"searchCell"];
    
    [self.view addSubview:_collectionView];
    
    nullView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    nullView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:nullView];
    
    UILabel *nullNote = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(126), SCREEN_WIDTH, ScreenX375(18))];
    nullNote.text = @"无搜索历史记录";
    nullNote.textColor = REXADECIMALCOLOR(@"#333333");
    nullNote.font = Kfont(13);
    nullNote.textAlignment = NSTextAlignmentCenter;
    [nullView addSubview:nullNote];
}

- (void)removeHistory {
    [_searchRecords removeAllObjects];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *document = paths[0];
    [_searchRecords writeToFile:[document stringByAppendingPathComponent:@"searchRecords.plist"] atomically:YES];
    [self getSearchRecords];
}

- (void)getSearchRecords {
    _searchRecords = [NSMutableArray array];
    //获取搜索记录
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *document = paths[0];
    NSString *plistPath = [document stringByAppendingPathComponent:@"searchRecords.plist"];
    //判断是否以创建文件
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
    {
        //如果没有plist文件就自动创建
        NSMutableArray *array = [NSMutableArray array];
        //写入文件
        [array writeToFile:plistPath atomically:YES];
    }
    _searchRecords = [NSMutableArray arrayWithContentsOfFile:plistPath];
    [_collectionView reloadData];
    
    if (_searchRecords.count == 0) {
        nullView.hidden = NO;
    }else {
        nullView.hidden = YES;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _searchRecords.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchCell" forIndexPath:indexPath];
    cell.layer.cornerRadius = ScreenX375(12);
    cell.backgroundColor = REXADECIMALCOLOR(@"#f3f3f3");
    cell.textLabel.text = _searchRecords[indexPath.item];
    cell.clipsToBounds = YES;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = _searchRecords[indexPath.item];
    CGRect rect = [key boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - ScreenX375(32), ScreenX375(24)) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:Kfont(12)} context:nil];
    return CGSizeMake(rect.size.width + ScreenX375(28), ScreenX375(24));
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [searchField resignFirstResponder];
    NSLog(@"搜索");
    
    //搜索方法
    [self searchClick];
    return NO;
}

- (void)searchClick{
    [searchField resignFirstResponder];

    //保存搜索记录
    if (![[searchField.text stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:@""]){
        NSString *str = [NSString stringWithFormat:@"%@",searchField.text];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *document = paths[0];
        NSString *plistPath = [document stringByAppendingPathComponent:@"searchRecords.plist"];
        if (![_searchRecords containsObject:str]) {
            [_searchRecords addObject:str];
            
            [_searchRecords writeToFile:plistPath atomically:YES];
            [_collectionView reloadData];
        }
    }
    
    searchField.text = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
